package com.hqyj.springbootday03.listener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * LogFileListener
 */
@WebListener
public class LogFileListener implements ServletContextListener {

	public static Logger LOGGER = LoggerFactory.getLogger(LogFileListener.class);

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		LOGGER.debug("======== 初始化 ServletContext 监听器 ========");

		// 获得目标文件夹，并判断其是否存在
		File destFolder = new File("/var/log");
		if (!destFolder.exists() || destFolder.isFile()) {
			return;
		}

		// 获取当前的时间字符串
		DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		String currentDate = dtf.format(LocalDateTime.now());

		// 找出目标文件夹的子文件进行循环，如果包含当前时间字符串则保留，否则删除
		File[] files = destFolder.listFiles();
		for (File file : files) {
			if (!file.getName().contains(currentDate)) {
				file.delete();
			}
		}
	}
}
